/**
 * @author Alejandro Gamboa. - alejogb15@gmail.com
 * @company UDistrital.
 */
package co.edu.udistrital.conce.presentacion;

import co.edu.udistrital.negocio.excepcion.ConcesionarioExcepcion;
import co.edu.udistrital.negocio.excepcion.ExcepcionSistema;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
import co.edu.udistrital.conce.presentacion.scope.ApplicationBean;
import co.edu.udistrital.conce.presentacion.scope.SessionBean;
import co.edu.udistrital.conce.presentacion.scope.RequestBean;
import co.edu.udistrital.negocio.base.AbstractVO;
import co.edu.udistrital.negocio.modelo.EstadoVO;
import co.edu.udistrital.negocio.modelo.InfoMantenimientoTO;
import co.edu.udistrital.negocio.modelo.InfoVehiculoTO;
import co.edu.udistrital.negocio.modelo.MantenimientoVO;
import co.edu.udistrital.negocio.modelo.RevisionVO;
import co.edu.udistrital.negocio.persistencia.EstadoDAO;
import co.edu.udistrital.negocio.persistencia.InfoMantenimientoView;
import co.edu.udistrital.negocio.persistencia.InfoVehiculoView;
import co.edu.udistrital.negocio.persistencia.ManejadorConexion;
import co.edu.udistrital.negocio.persistencia.MantenimientoDAO;
import co.edu.udistrital.negocio.persistencia.RevisionDAO;
import co.edu.udistrital.util.SelectItemUtils;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import javax.faces.model.SelectItem;


/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 */
public class MantenimientoAutoPage extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    private Connection connection;
    private String placa;
    private Collection<InfoVehiculoTO> listaVehiculos;
    private Collection<InfoMantenimientoTO> listaMantenimientos;
    private ArrayList<AbstractVO> revisiones;
    private ArrayList<AbstractVO> estados;
    private List<SelectItem> listaRevisiones;
    private List<SelectItem> listaEstados;
    private InfoVehiculoTO vehiculoTO;
    private String estadoId;
    private String revisionId;
    private String recibidoPor;
    private BigDecimal kilometraje;
    private boolean flagDetalle;
    private boolean flagMantenimiento;
    private boolean flagRegMantenimiento;

    public String getEstadoId() {
        return estadoId;
    }

    public void setEstadoId(String estadoId) {
        this.estadoId = estadoId;
    }

    public BigDecimal getKilometraje() {
        return kilometraje;
    }

    public void setKilometraje(BigDecimal kilometraje) {
        this.kilometraje = kilometraje;
    }

    public String getRecibidoPor() {
        return recibidoPor;
    }

    public void setRecibidoPor(String recibidoPor) {
        this.recibidoPor = recibidoPor;
    }

    public String getRevisionId() {
        return revisionId;
    }

    public void setRevisionId(String revisionId) {
        this.revisionId = revisionId;
    }

    public InfoVehiculoTO getVehiculoTO() {
        return vehiculoTO;
    }

    public void setVehiculoTO(InfoVehiculoTO vehiculoTO) {
        this.vehiculoTO = vehiculoTO;
    }

    public List<SelectItem> getListaEstados() {
        return listaEstados;
    }

    public void setListaEstados(List<SelectItem> listaEstados) {
        this.listaEstados = listaEstados;
    }

    public List<SelectItem> getListaRevisiones() {
        return listaRevisiones;
    }

    public void setListaRevisiones(List<SelectItem> listaRevisiones) {
        this.listaRevisiones = listaRevisiones;
    }

    public ArrayList<AbstractVO> getEstados() {
        return estados;
    }

    public void setEstados(ArrayList<AbstractVO> estados) {
        this.estados = estados;
    }

    public ArrayList<AbstractVO> getRevisiones() {
        return revisiones;
    }

    public void setRevisiones(ArrayList<AbstractVO> revisiones) {
        this.revisiones = revisiones;
    }

    public boolean isFlagRegMantenimiento() {
        return flagRegMantenimiento;
    }

    public void setFlagRegMantenimiento(boolean flagRegMantenimiento) {
        this.flagRegMantenimiento = flagRegMantenimiento;
    }

    public Collection<InfoMantenimientoTO> getListaMantenimientos() {
        return listaMantenimientos;
    }

    public void setListaMantenimientos(Collection<InfoMantenimientoTO> listaMantenimientos) {
        this.listaMantenimientos = listaMantenimientos;
    }

    public boolean isFlagDetalle() {
        return flagDetalle;
    }

    public void setFlagDetalle(boolean flagDetalle) {
        this.flagDetalle = flagDetalle;
    }

    public boolean isFlagMantenimiento() {
        return flagMantenimiento;
    }

    public void setFlagMantenimiento(boolean flagMantenimiento) {
        this.flagMantenimiento = flagMantenimiento;
    }
    
    public Collection<InfoVehiculoTO> getListaVehiculos() {
        return listaVehiculos;
    }

    public void setListaVehiculos(Collection<InfoVehiculoTO> listaVehiculos) {
        this.listaVehiculos = listaVehiculos;
    }

    public Connection getConnection() throws ExcepcionSistema {
        if ( connection ==null ){
            connection = ManejadorConexion.obtenerConexion();
        }
        return connection;
    }

    public String getPlaca() {
        return placa;
    }

    public void setPlaca(String placa) {
        this.placa = placa;
    }


    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }


    // </editor-fold>

    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public MantenimientoAutoPage() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here
            
        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("WelcomePage Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        
        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {

    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean getscope$ApplicationBean() {
        return (ApplicationBean) getBean("scope$ApplicationBean");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean getscope$SessionBean() {
        return (SessionBean) getBean("scope$SessionBean");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean getscope$RequestBean() {
        return (RequestBean) getBean("scope$RequestBean");
    }

    public String buscar (){
        try {
            InfoVehiculoView view = new InfoVehiculoView(getConnection());
            this.placa = this.placa.toUpperCase();
            this.flagDetalle = true;
            this.flagMantenimiento = false;
            this.flagRegMantenimiento = false;
            this.listaVehiculos = view.queryByWhere("placa='"+this.placa+"'");
            if ( this.listaVehiculos ==null || this.listaVehiculos.isEmpty() ){
                error("El vehículo con la placa "+this.placa+" no se encuentra registrado en el sistema.");
                this.flagDetalle = false;
                return null;
            }
        } catch (Exception ex) {
            Logger.getLogger(MantenimientoAutoPage.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public String verDetalle (){
        try {
            this.vehiculoTO = (InfoVehiculoTO) this.getValue("#{row}");
            getDetalle(vehiculoTO);
        } catch (Exception ex) {
            Logger.getLogger(MantenimientoAutoPage.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    private void getDetalle(InfoVehiculoTO to) throws ExcepcionSistema, ConcesionarioExcepcion{
        InfoMantenimientoView view = new InfoMantenimientoView(getConnection());
            this.flagMantenimiento = true;
            this.flagRegMantenimiento = false;
            this.listaMantenimientos = view.queryByWhere("vehiculo_id='"+to.getId()+"'");
            if ( this.listaMantenimientos ==null || this.listaMantenimientos.isEmpty() ){
                error("El vehículo con la placa "+to.getPlaca()+" no tiene mantenimientos registrados");
                //this.flagMantenimiento = false;
            }
    }

    public String hacerMantenimiento (){
        try {
            RevisionDAO revDao = new RevisionDAO(getConnection());
            EstadoDAO estadoDao = new EstadoDAO(getConnection());
            this.revisiones = revDao.findByWhereString(new RevisionVO(), "1=1");
            this.estados = estadoDao.findByWhereString(new EstadoVO(), "1=1");
            this.listaEstados = SelectItemUtils.buildObjectSelectItems(this.estados, "id", "nombre", false);
            List<AbstractVO> temp = new ArrayList<AbstractVO>();
            for (AbstractVO vo : this.revisiones ){
                for ( InfoMantenimientoTO to : this.listaMantenimientos ){
                    if ( to.getRevisionId().equals(((RevisionVO)vo).getId()) ){
                        temp.add(vo);
                    }
                }
            }
            this.revisiones.removeAll(temp);
            this.listaRevisiones = SelectItemUtils.buildObjectSelectItems(this.revisiones, "id", "kilometraje", false);
            this.flagRegMantenimiento = true;
        } catch (Exception ex) {
            Logger.getLogger(MantenimientoAutoPage.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public String registrarMantenimiento() {
        try {
            Calendar cal = Calendar.getInstance();
            MantenimientoDAO manteDao = new MantenimientoDAO(getConnection());
            MantenimientoVO vo = new MantenimientoVO();
            vo.setId(UUID.randomUUID().toString());
            vo.setVehiculoId(this.vehiculoTO.getId());
            vo.setRevisionId(this.revisionId);
            vo.setEstadoId(this.estadoId);
            vo.setFechaEntrada(cal);
            vo.setFechaSalida(cal);
            vo.setRecibidoPor(this.recibidoPor);
            vo.setKilometraje(this.kilometraje);
            vo.setComentarios("");
            manteDao.insert(vo);
            getDetalle(this.vehiculoTO);
            info("Mantenimiento registrado con éxito");
        } catch (Exception ex) {
            error("No se pudo registrar el mantenimiento. Por favor consulte con el Administrador.");
            Logger.getLogger(MantenimientoAutoPage.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

}

